<template>
  <div class="flex-container" style="background-color: #f4f5f6;">
    <!-- 标题栏 -->
    <div class="divider"></div>
    <van-pull-refresh
      v-model="outOfStockRefreshing"
      @refresh="outOfStockOnRefresh(true)"
      style="flex: auto;overflow: auto;"
    >
      <van-list
        id="outOfStock"
        v-model="outOfStockLoading"
        :finished="outOfStockFinished"
        finished-text="没有更多了"
        @load="outOfStockLoad"
      >
        <van-cell>
          <ul>
            <li class="contLi" v-for="(item,index) in dataList" :key="index">
              <div class="left">
                <div class="leftLi">
                  <span class="title">出库单单号</span>
                  <span class="desc">{{item.number}}</span>
                </div>
                <div class="leftLi">
                  <span class="title">申请人</span>
                  <span class="desc">{{item.applyName}}</span>
                </div>
                <div class="leftLi">
                  <span class="title">单据涞源</span>
                  <span class="desc">{{item.source}}</span>
                </div>
                <div class="leftLi">
                  <span class="title">申请时间</span>
                  <span class="desc">{{item.time}}</span>
                </div>
              </div>
              <div class="right-arrow-style">
                <img src="@/assets/ic_right_arrow.png" width="37%" height="37%" />
              </div>
            </li>
          </ul>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import http from "@/utils/request";
import api from "@/utils/api";
import { Dialog } from "vant";
import Toast from "@/utils/toast";
import consts from "@/utils/consts";
export default {
  name: "OutOfStorage",
  // props: ["keywords", "state"],
  data() {
    return {
      dataList: [
        {
          number: "CK2910060601",
          applyName: "张三",
          source: "血液制品部",
          time: "2020-05-19"
        }
      ],

      page: 0,
      pageSize: 10,
      totalCount: 0,
      pageCount: 0,
      order: "",
      barCode: [], //扫码到的条形码

      stateList: [
        {
          value: consts.allState,
          name: "全部"
        },
        { value: 1, name: "未确认" },
        { value: 2, name: "待确认" },
        { value: 3, name: "待提交" },
        { value: 4, name: "待审批" },
        { value: 5, name: "已出库" },
        { value: 6, name: "已拒绝" }
      ],

      applyCode: 0, //领料单单号
      // outOfStorageId: 0, //出库单ID
      // nums: 0, //库存数量
      // count: 0, //出库数量
      // selectNums: 0, //已扫码的数量
      // name: "", //名字
      // shelveNames: "", //货架
      // code: "", //code
      // batchCode: "", //批号
      // applyRemark: "", //领料备注
      outStorageList: [],
      // shelveArray: [], //存储位置
      // state: 0, //状态
      // outOfStorageDetail: {
      //   outOfStorageId: "", //出库单ID
      //   nums: 0, //库存数量
      //   count: 0, //出库数量
      //   selectNums: 0, //已扫码的数量
      //   name: "", //名字
      //   prodBatchCode: "", //批号
      //   shelveName: "" //货架
      // }, //出库明细
      // rejectDialogShow: false,
      // submitDialogShow: false,
      // rejectRemark: "",
      // submitRemark: "",
      outOfStockLoading: false,
      outOfStockFinished: false,
      outOfStockRefreshing: false
    };
  },
  methods: {
    onBackClick() {
      //先保存
      // this.outStorageList.forEach(item => {
      //   this.save(item);
      // });
      // this.barCodeScanOutStorage("20190823000025");
      this.$router.push({
        path: "/main",
        query: { active: "materialRequisition" }
      });
    },
    getcardStyle(index) {
      if (this.barCode.length == 0 || index > 0) {
        return "card";
      } else {
        return "attentionCard";
      }
      // if (index > 0) {
      //   return "card";
      // } else {
      //   return "attentionCard";
      // }
    },
    formatBatchCode(batchCode) {
      if (!batchCode) {
        return "暂无";
      } else {
        const batchCodeArray = batchCode.split(",");
        console.log(batchCodeArray);

        let batchCodeString = "";
        for (let i = 0; i < batchCodeArray.length; i++) {
          if (i > 0) {
            // batchCodeString += "批号: "
            //加空格，对齐
            batchCodeString += "\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0";
          }
          batchCodeString += batchCodeArray[i];
          if (i < batchCodeArray.length - 1) {
            batchCodeString += "\r\n";
          }
        }
        return batchCodeString;
      }
    },
    sortByState(a, b) {
      return a.state - b.state;
    },
    //置顶
    shiftToTop(array, index) {
      if (index > array.length - 1) {
        return;
      }
      var items = array.splice(index, 1);
      array.unshift(items[0]);
    },
    outOfStockLoad() {
      console.log("outOfStockLoad");
      this.outOfStockLoading = true;
      let param = {
        applyCode: this.applyCode,
        // page: this.page + 1,
        // pageSize: this.pageSize,
        name: this.keywords,
        state: this.state == consts.allState ? consts.outStorageAll : this.state
      };
      http
        .fetchGet(api.outOfStorageAll, param)
        .then(data => {
          // if (!data.data || data.page >= data.pageCount) {
          //   this.outOfStockFinished = true;
          // }
          // this.page = data.page;

          // this.outStorageList = this.outStorageList.concat(data.data);
          // this.outStorageList.sort(this.sortByState);
          // this.outOfStockLoading = false;

          //添加submitFailed字段，否则v-if无法绑定submitFailed字段
          data.forEach(item => {
            item.submitFailed = false;
          });
          if (data) {
            this.outStorageList = data;
            this.outStorageList.sort(this.sortByState);
            this.outOfStockLoading = false;
            this.outOfStockFinished = true;
          }
        })
        .catch(err => {
          this.outOfStockLoading = false;
          this.outOfStockFinished = true;
        });
    },
    outOfStockOnRefresh(showMsg = false) {
      console.log("outOfStockOnRefresh");
      // this.page = 0;
      let param = {
        applyCode: this.applyCode
        // page: this.page + 1,
        // pageSize: this.pageSize
      };
      if (this.keywords) {
        param.name = this.keywords;
      }
      if (this.state != consts.allState) {
        param.state = this.state;
      } else {
        param.state = consts.outStorageAll;
      }
      http
        .fetchGet(api.outOfStorageAll, param)
        .then(data => {
          // if (!data.data || data.page >= data.pageCount) {
          //   this.outOfStockFinished = true;
          // }
          // this.page = data.page;

          // this.outStorageList = data.data;
          // this.outStorageList.sort(this.sortByState);
          // this.outOfStockRefreshing = false;
          data.forEach(item => {
            item.submitFailed = false;
          });
          if (data) {
            this.outStorageList = data;
            this.outStorageList.sort(this.sortByState);
            this.outOfStockLoading = false;
            this.outOfStockFinished = true;
            this.outOfStockRefreshing = false;
          }
          if (showMsg) {
            Toast.toast("刷新成功");
          }
        })
        .catch(err => {
          this.outOfStockRefreshing = false;
          this.outOfStockFinished = true;
        });
    },
    //让用户确认出库
    submitOneConfirm(item) {
      if (item.selectNums < item.count) {
        Toast.toast("领取数量不够！", false);
      } else {
        // this.submitDialogShow = true;
        Dialog.confirm({
          title: "提交",
          message: "确认提交" + item.name + "吗？"
        })
          .then(() => {
            // on confirm
            this.submitOne(item);
          })
          .catch(() => {
            // on cancel
          });
      }
    },
    //提交出库单，,当物料扫码扫满后，自动提交这个物料
    submitOne(item) {
      console.log("submitOne");
      let params = {
        outStorageId: item.id,
        isConfirm: false,
        isSubmit: true
      };
      http
        .fetchPost(api.outOfStorageSubmit, params, "正在提交")
        .then(data => {
          Toast.toast("提交成功");
          this.outOfStockOnRefresh(false);
          // this.onBackClick();
        })
        .catch(err => {
          //提交失败，显示提交按钮，供用户再次提交
          item.submitFailed = true;
          console.log("submitFailed");
        });
    },
    //让用户确认拒绝出库
    rejectStorageOutConfirm(item) {
      Dialog.confirm({
        title: "拒绝出库",
        message: "确认拒绝出库" + item.name + "吗?"
      })
        .then(() => {
          // on confirm
          this.rejectStorageOut(item);
        })
        .catch(() => {
          // on cancel
        });
    },
    rejectStorageOut(item) {
      console.log("rejectStorageOut");
      let params = {
        outStorageId: item.id,
        isConfirm: true,
        isSubmit: true
      };
      http
        .fetchPost(api.outOfStorageSubmit, params, "正在拒绝")
        .then(data => {
          Toast.toast("拒绝成功");
          // this.onBackClick();
        })
        .catch(err => {});
    },
    save(item) {
      console.log("save");
      let params = {
        outStorageId: item.id,
        isConfirm: false,
        isSubmit: false
      };
      http
        .fetchPost(api.outOfStorageSubmit, params)
        .then(data => {
          // Toast.success("提交成功");
          // this.onBackClick();
        })
        .catch(err => {});
    },
    onSearch() {
      console.log("onSearch");
      this.$store.commit("setOutStockKeywords", this.keywords);
    },
    onCancel() {
      console.log("onCancel");
      this.$store.commit("setOutStockKeywords", null);
    },
    showOutOfStockDetail(index) {
      let outOfStock = this.outStorageList[index];
      this.$router.push({
        path: "/outOfStorageDetail",
        query: {
          id: outOfStock.id,
          nums: outOfStock.nums,
          count: outOfStock.count,
          selectNums: outOfStock.selectNums,
          name: outOfStock.name,
          code: outOfStock.code,
          batchCode: outOfStock.batchCode,
          applyRemark: outOfStock.applyRemark,
          state: outOfStock.state,
          applyUserName: outOfStock.applyUserName,
          applyCode: this.applyCode
        }
      });
    },
    //让用户确认
    submitConfirm() {
      Dialog.confirm({
        title: "提交",
        message: "提交此物料出库，并由仓库主管进行审核？"
      })
        .then(() => {
          // on confirm
          this.submitAll();
        })
        .catch(() => {
          // on cancel
        });
    },
    //提交单据
    submitAll() {
      // this.barCodeScanOutStorage("20190816000042");
      // this.submitOne(this.outStorageList[0]);

      console.log("storageOutSubmitAll");
      let params = {
        applyCode: this.applyCode
      };
      http
        .fetchGet(api.outOfStorageSubmitAll, params, "正在提交")
        .then(data => {
          this.$store.commit("removeInProcess", this.applyCode);
          Toast.toast("提交成功");
          this.onBackClick();
        })
        .catch(err => {});
    },
    barCodeScanOutStorage(code) {
      let isDuplicate = false;
      for (var i = 0; i < this.barCode.length; i++) {
        if (this.barCode[i] == code) {
          isDuplicate = true;
          break;
        }
      }
      if (isDuplicate) {
        Toast.toast("重复的条形码", false);
      } else {
        this.barCodeValid(code);
      }
    },
    barCodeValid(code) {
      let params = {
        applyCode: this.applyCode,
        barCode: code
      };
      http
        .fetchGet(api.outOfStorageBarCodeValid, params, "正在扫码条码")
        .then(data => {
          // Toast.success("校验成功");
          if (!data) {
            return;
          }
          console.log(data);
          // if (data.isSave) {
          console.log("saved");
          this.$store.commit("addInProcess", this.applyCode);
          Toast.toast("扫码成功");
          this.barCode.push(code);
          const outStorage = this.outStorageList.find(item => {
            return item.id == data.outStorageId;
          });
          console.log(outStorage);
          if (outStorage) {
            outStorage.selectNums++;
            const index = this.outStorageList.indexOf(outStorage);
            this.shiftToTop(this.outStorageList, index);
            //扫码扫满后自动提交
            // if (outStorage.selectNums == outStorage.count) {
            //   this.submitOne(outStorage);
            // }
          }
          if (this.$route.query.barCode == code) {
            this.outOfStockOnRefresh(false);
          }
          // } else {
          //   Toast.toast("校验失败", false);
          // }
        })
        .catch(err => {});
    },
    //让用户确认拒绝出库
    // rejectStorageOutConfirm() {
    //   // this.barCodeScanOutStorage("20190708000001");
    //   this.rejectDialogShow = true;
    // },
    // rejectStorageOut() {
    //   console.log("rejectStorageOut");
    //   let params = {
    //     outStorageId: this.outOfStorageId,
    //     remark: this.rejectRemark,
    //     isConfirm: true
    //   };
    //   http
    //     .fetchPost(api.outOfStorageSubmit, params)
    //     .then(data => {
    //       Toast.success("拒绝成功");
    //       this.onBackClick();
    //     })
    //     .catch(err => {});
    // },
    getOutOfStorageStateStr(item) {
      // if (state == 1) {
      //   return "未确认";
      // } else if (state == 2) {
      //   return "待确认";
      // } else if (state == 3) {
      //   return "待提交";
      // } else if (state == 4) {
      //   return "待审批";
      // } else if (state == 5) {
      //   return "已出库";
      // } else if (state == 6) {
      //   return "已拒绝";
      // }

      // if (state == 1 || state == 2 || state == 3) {
      //   return "待处理";
      // } else if (state == 4 || state == 5 || state == 6) {
      //   return "已完成";
      // }

      if (item.selectNums < item.count) {
        return "待处理";
      } else {
        return "已完成";
      }
    }
  },
  computed: {
    keywords: {
      get() {
        return this.$store.getters.outStockKeywords;
      },
      set(val) {
        this.$store.commit("setOutStockKeywords", val);
        this.outOfStockOnRefresh(false);
      }
    },
    state: {
      get() {
        return this.$store.getters.outStockState;
      },
      set(val) {
        this.$store.commit("setOutStockState", val);
        this.outOfStockOnRefresh(false);
      }
    },
    //如果提交过了，则不显示提交按钮
    isShowSubmit() {
      if (this.outStorageList == null || this.outStorageList.length == 0) {
        return false;
      } else {
        return !this.outStorageList.some(function(item) {
          // return item.state > 3;
          return item.state < 3;
        });
      }
    }
  },
  // watch: {
  //   keywords() {
  //     this.outOfStockOnRefresh(true);
  //   }
  // },
  created() {
    this.applyCode = this.$route.query.applyCode;
    const barCode = this.$route.query.barCode;
    if (barCode) {
      this.barCodeScanOutStorage(barCode);
    }
    window.barCodeScanOutStorage = this.barCodeScanOutStorage;
  },
  beforeDestroy() {
    window.barCodeScanOutStorage = null;
  }
};
</script>

<style lang="scss" scoped>
.contLi {
  padding: 8px;
  box-sizing: border-box;
  display: flex;
  font-size: 20px;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  margin-top: 10px;
}
.left {
  width: 70%;
  text-align: left;
}
.leftLi {
  display: flex;
  line-height: 30px;
}
.title {
  min-width: 33%;
}
.desc {
  margin-left: 20px;
}
.right-arrow-style {
  margin-left: 50px;
}

.divider {
  height: 1px;
  width: 100%;
  background-color: #e6e6e6;
}
.flex-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
:nth-child(1),
:nth-child(2),
:nth-child(4) {
  flex-shrink: 0;
  flex-grow: 0;
}
:nth-child(3) {
  flex-shrink: 1;
  flex-grow: auto;
  overflow: auto;
}

.content:nth-child(2) {
  align-content: flex-end;
}
.card {
  // border-width: 0 0 1px 0;
  // border-style: solid;
  // border-color: #cccccc;
  // margin-left: 5px;
  // margin-right: 5px;
  // background-color: white;
  // width: auto;
  // padding: 5px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
  background-color: white;
  width: auto;
  padding: 14px 16px 14px 16px;
}

.van-cell {
  padding: 0;
}
.attentionCard {
  border-width: 2px;
  border-style: solid;
  border-color: lightblue;
  border-radius: 5px;
  margin-left: 5px;
  margin-right: 5px;
  background-color: white;
  width: auto;
  padding: 5px;
}
/* 物料名称 */
.materialName {
  color: black;
  display: block;
  font-size: 26px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(51, 51, 51, 1);
  line-height: 37px;
  letter-spacing: 1px;
}

// 编号
.code {
  color: black;
  display: block;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(102, 102, 102, 1);
  line-height: 30px;
  letter-spacing: 1px;
}

/* 领取数/出库数 */
.storageCount {
  color: black;
  display: block;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(153, 153, 153, 1);
  line-height: 30px;
  letter-spacing: 1px;
}

.textLeft {
  text-align: left;
}

.未确认,
.待确认,
.待提交,
.待审批 {
  text-align: center;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(245, 149, 62, 1);
  line-height: 30px;
  letter-spacing: 1px;
}
.已出库 {
  // color: #00ff66;
  text-align: center;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(112, 211, 111, 1);
  line-height: 30px;
  letter-spacing: 1px;
}
.已拒绝 {
  text-align: center;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: red;
  line-height: 30px;
  letter-spacing: 1px;
}
//浓缩后的状态
.待处理 {
  text-align: center;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(245, 149, 62, 1);
  line-height: 30px;
  letter-spacing: 1px;
}
.已完成 {
  text-align: center;
  font-size: 22px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(112, 211, 111, 1);
  line-height: 30px;
  letter-spacing: 1px;
}

.footer {
  // z-index: 9999;
  position: fixed;
  bottom: 0px;
  width: 100%;
  /* height: h px; */
}
.roundButton {
  width: 100%;
  height: 60px;
  font-size: 26px;
  font-family: PingFangSC-Regular;
  font-weight: 400;
  color: rgba(255, 255, 255, 1);
  line-height: 45px;
  letter-spacing: 1px;
  background: rgba(71, 124, 236, 1);
}
.stateSelect {
  height: 30px;
  width: 80px;
  background: white;
  color: #7542de;
  line-height: 28px;
  border: 1px solid #9bc0dd;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
}
</style>
